package model

import (
	"ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Article struct {
	Category Category `gorm:"foreignkey:Cid"`
	gorm.Model
	Title        string `gorm:"type:varchar(100);not null" json:"title"`
	Cid          int    `gorm:"type:int;not null" json:"cid"`
	Desc         string `gorm:"type:varchar(200)" json:"desc"`
	Content      string `gorm:"type:longtext" json:"content"`
	Img          string `gorm:"type:varchar(100)" json:"img"`
	CommentCount int    `gorm:"type:int;not null;default:0" json:"comment_count"`
	ReadCount    int    `gorm:"type:int;not null;default:0" json:"read_count"`
}

// CreatArticle  创建文章
func CreatArticle(data *Article) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

func GetArticle(id int) Article {
	var article Article
	err := db.Where("id=?", id).First(&article).Error
	if err != nil {
		return article
	}
	return article
}

// GetCateArticle 获取分类下文章
func GetCateArticle(id int, pageSize int, pageNum int) []Article {
	var article []Article
	err = db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("cid", id).Find(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil
	}
	return article

}

// GetArticleList  获取文章列表
func GetArticleList(pageSize int, pageNum int) []Article {

	var article []Article
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&article).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil
	}
	return article
}

// DelArticle 删除文章
func DelArticle(id int) int {
	var article Article
	db.Select("id").Where("id=?", id).First(&article)
	if article.ID >= 1 {
		db.Where("id = ?", id).Delete(&article)
		return errmsg.SUCCSE
	}
	return errmsg.ERROR_ART_NOT_EXIST
}

// EdtArticle 修改文章
func EdtArticle(id int, data *Article) int {
	var category Article

	var maps = make(map[string]interface{})
	maps["Title"] = data.Title
	maps["Cid"] = data.Cid
	maps["Desc"] = data.Desc
	maps["Content"] = data.Content
	maps["Img"] = data.Img

	errs := db.Model(&category).Where("id=?", id).Updates(maps).Error
	if errs != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}
